openCV uses pass by reference not pythonic pass by value

by: skypickle, 9 years ago


This code is taken from lesson5 of the openCV tutorial
https://pythonprogramming.net/image-arithmetics-logic-python-opencv-tutorial/


import cv2
import numpy as np

# Load two images
img1 = cv2.imread('3D-Matplotlib.png')
#img1a = img1
img1a = cv2.imread('3D-Matplotlib.png')
img2 = cv2.imread('mainlogo.png')
img3 = cv2.imread('helloo.png')
# I want to put logo on top-left corner, So I create a ROI
rows,cols,channels = img2.shape
roi = img1[20:rows+20, 20:cols+20]

rows3,cols3,channels3 = img3.shape
roi3 = img1[50:rows3+50, 50:cols3+50 ]


# Now create a mask of logo
img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
# add a threshold
ret, mask = cv2.threshold(img2gray, 220, 255, cv2.THRESH_BINARY_INV)
#anything crossing over 220 is thelower limit
#binary threshold is 0 or 1
#anything> 220 goes to 255
#anything below 220 goes to 0-> black
#and create its inverse mask
mask_inv = cv2.bitwise_not(mask)
#do same for img3
img3gray = cv2.cvtColor(img3,cv2.COLOR_BGR2GRAY)
ret3, mask3 = cv2.threshold(img3gray, 140, 255, cv2.THRESH_BINARY_INV)
mask_inv3 = cv2.bitwise_not(mask3)


# take the ROI of the plot, and throw the mask over it
img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)

# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2,img2,mask = mask)

#do the same with the other mask
img3_bg = cv2.bitwise_and(roi3,roi3,mask = mask_inv3)
img3_fg = cv2.bitwise_and(img3,img3,mask = mask3)
#

dst = cv2.add(img1_bg,img2_fg)
dst3 = cv2.add(img3_bg,img3_fg)

img1[0:rows, 0:cols ] = dst
img1a[50:rows3+50, 50:cols3+50 ] = dst3

cv2.imshow('r1',img1)
cv2.imshow('r3',img1a)

cv2.waitKey(0)
cv2.destroyAllWindows()


run it.
now comment out line 7 and uncomment line 8.
run it again and get a different result.

why?



You must be logged in to post. Please login or register an account.



One is a copy of the other, modifying the same object apparently, the other is a new one. Nice find. Not what one would expect to occur with Python!

-Harrison 9 years ago
Last edited 9 years ago

You must be logged in to post. Please login or register an account.